package com.lanou.sfu.songforu.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.activity.MainActivity;
import com.lanou.sfu.songforu.datas.MusicListDatas;
import com.lanou.sfu.songforu.datas.SongInfors;
import com.lanou.sfu.songforu.singleton.VolleySingleton;
import com.lanou.sfu.songforu.tools.BaseTools;
import com.lanou.sfu.songforu.view.MusicInterface;
import com.lanou.sfu.songforu.view.MyEvent;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;


/**
 * Created by quyan on 15/10/30.
 */
public class PlayerService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener {
    // 播放模式
    public static final int MPM_LIST_LOOP_PLAY = 0; // 列表循环
    public static final int MPM_ORDER_PLAY = 1; // 顺序播放
    public static final int MPM_RANDOM_PLAY = 2; // 随机播放
    public static final int MPM_SINGLE_LOOP_PLAY = 3; // 单曲循环

    /**
     * 通知栏按钮广播
     */
    public ButtonBroadcastReceiver bReceiver;
    /**
     * 通知栏按钮点击事件对应的ACTION
     */
    public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";
    public final static String INTENT_BUTTONID_TAG = "ButtonId";
    /**
     * 上一首 按钮点击 ID
     */
    public final static int BUTTON_PREV_ID = 1;
    /**
     * 播放/暂停 按钮点击 ID
     */
    public final static int BUTTON_PALY_ID = 2;
    /**
     * 下一首 按钮点击 ID
     */
    public final static int BUTTON_NEXT_ID = 3;
    /**
     * 清除通知栏 按钮点击
     **/
    public final static int BUTTON_EXIT_ID = 4;
    //跳转Activity
    public final static int BUTTON_INTENT_ID = 5;
    /**
     * Notification管理
     */
    public NotificationManager mNotificationManager;
    private String musicUrl;

    public static MediaPlayer mediaPlayer;//定义一个音频对象
    private Timer timer;
    private boolean prepare = false;
    private VolleySingleton volleySingleton;
    private String name;
    private String singer, image;
    private ArrayList<MusicListDatas> listDatases;
    private int index;
    private int mPlayMode;//播放模式
    private RemoteViews mRemoteViews;
    private NotificationCompat.Builder mBuilder;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MediaBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        EventBus.getDefault().register(this);//订阅
        Log.i("cxh", "服务开启");
        mediaPlayer = new MediaPlayer();
        volleySingleton = VolleySingleton.getInstance(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);
        mPlayMode = MPM_LIST_LOOP_PLAY;
        listDatases = new ArrayList<>();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        initButtonReceiver();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (mediaPlayer != null) {
            mediaPlayer.reset();//重置
            mediaPlayer.release();//释放
            mediaPlayer = null;
        }
        return super.onUnbind(intent);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        //prepare = true;
        mediaPlayer.start();
        addTimer();

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    class MediaBinder extends Binder implements MusicInterface {

        @Override
        public void play(ArrayList<MusicListDatas> lists, int position) {
            listDatases = lists;
            index = position;
            PlayerService.this.play(lists, position);
            showButtonNotify();
        }

        @Override
        public void clean() {

        }

        @Override
        public void pause() {
            PlayerService.this.pause();

        }

        @Override
        public void continuePlay() {
            PlayerService.this.continuePlay();

        }

        @Override
        public void seekTo(int progress) {
            PlayerService.this.seekTo(progress);
        }

        @Override
        public boolean getIsPlay() {
            return PlayerService.this.getIsPlay();
        }

        @Override
        public int getDuration() {
            return mediaPlayer.getDuration();
        }

        @Override
        public int getProgress() {
            return mediaPlayer.getCurrentPosition();
        }

        @Override
        public String getName() {
            return PlayerService.this.getName();
        }

        @Override
        public String getSinger() {
            return PlayerService.this.getSinger();
        }

        @Override
        public String getImage() {
            return PlayerService.this.getImage();
        }

        @Override
        public void next() {
            PlayerService.this.next();
        }

        @Override
        public void upSong() {
            PlayerService.this.upSong();
        }

        @Override
        public ArrayList<MusicListDatas> musicList() {
            return PlayerService.this.getMsuicList();
        }

        @Override
        public String getUrl() {
            return PlayerService.this.getUrl();
        }

        @Override
        public void playMode(int mode) {
            mPlayMode = mode;
        }

    }

    //下一首
    public void next() {
        switch (mPlayMode) {
            case 0:
            case 1:
            case 3:
                if (listDatases != null && listDatases.size() > 0) {
                    if (index + 1 > listDatases.size() - 1) {
                        index = 0;
                    } else {
                        index++;
                    }
                    play(listDatases, index);
                }
                break;
            case 2:
                index = new Random().nextInt(listDatases.size());
                play(listDatases, index);
                break;
        }

    }

    //上一首
    public void upSong() {
        switch (mPlayMode) {
            case 0:
            case 1:
            case 3:
                if (listDatases != null && listDatases.size() > 0) {
                    if (index + 1 > listDatases.size() - 1) {
                        index = 0;
                    } else {
                        index--;
                    }
                    play(listDatases, index);
                }
                break;
            case 2:
                index = new Random().nextInt(listDatases.size());
                play(listDatases, index);
                break;
        }
    }

    //播放音乐
    public void play(ArrayList<MusicListDatas> lists, final int position) {
        Log.i("Sysout", "position" + position);
        //判断是否为null 不为null 退出任务
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (lists.get(position).getFrom().equals("网络")) {
            name = lists.get(position).getName();
            singer = lists.get(position).getSinger();
            image = lists.get(position).getSingerImage();
            //重置资源
            String songid = lists.get(position).getSongId();
            Log.i("hhhh", songid);
            final String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    songid + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    String str = response.toString();
                    SongInfors infors = JSON.parseObject(str, SongInfors.class);
                    musicUrl = infors.getSonginfo().getLrclink();
                    String url = !infors.getSongurl().getUrl().get(0).getShow_link().isEmpty() ? infors.getSongurl().getUrl().get(0).getShow_link() : infors.getSongurl().getUrl().get(1).getShow_link();
//                    mediaPlayer.release();
//                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    //加载多媒体文件
                    try {
                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.stop();
                        }
                        prepare = true;
                        showButtonNotify();
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(url);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            volleySingleton.addQueue(jr, "PlayerService");
        } else if (lists.get(position).getFrom().equals("本地")) {
            name = lists.get(position).getName();
            singer = lists.get(position).getSinger();
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //加载多媒体文件
            try {
                mediaPlayer.setDataSource(lists.get(position).getSongId());
                mediaPlayer.prepareAsync();
                prepare = true;
                showButtonNotify();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (lists.get(position).getFrom().equals("搜索")) {
            name = lists.get(position).getName();
            singer = lists.get(position).getSinger();
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mediaPlayer.setDataSource(lists.get(position).getSongId());
                mediaPlayer.prepare();
                prepare = true;
                showButtonNotify();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //是否播放

    public boolean getIsPlay() {
        return mediaPlayer.isPlaying();
    }

    //播放
    public void continuePlay() {
        mediaPlayer.start();
        prepare = true;
        showButtonNotify();
    }

    public String getUrl() {
        return musicUrl;
    }

    //暂停
    public void pause() {
        mediaPlayer.pause();
        prepare = false;
        showButtonNotify();
    }

    //进度条
    public void seekTo(int progress) {
        mediaPlayer.seekTo(progress);
    }

    public int getDuration() {
        int i = 0;
        if (prepare) {
            i = mediaPlayer.getDuration();
        }
        return i;
    }

    public int getProgress() {
        int i = 0;
        if (prepare) {
            i = mediaPlayer.getCurrentPosition();
        }
        return i;
    }

    public String getName() {
        return name;
    }

    public String getSinger() {
        return singer;
    }

    public String getImage() {
        return image;
    }

    public ArrayList<MusicListDatas> getMsuicList() {
        return listDatases;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (listDatases.size() > 0) {
            switch (mPlayMode) {
                case MPM_LIST_LOOP_PLAY:
                    if (index == listDatases.size() - 1)
                        index = 0;
                    else
                        index++;
                    play(listDatases, index);
                    break;
                case MPM_ORDER_PLAY:
                    if (index == listDatases.size() - 1) {
                    } else {
                        index++;
                        play(listDatases, index);
                    }
                    break;
                case MPM_RANDOM_PLAY:
                    index = new Random().nextInt(listDatases.size());
                    play(listDatases, index);
                    break;
                case MPM_SINGLE_LOOP_PLAY:
                    play(listDatases, index);
                    break;
            }
        }
    }

    /**
     *  TimerTask是个抽象类,实现了Runnable接口，所以TimerTask就是一个子线程
     *  Timer就是一个线程，使用schedule方法完成对TimerTask的调度，多个TimerTask可以共用一个Timer，
     *  也就是说Timer对象调用一次schedule方法就是创建了一个线程，并且调用一次schedule后TimerTask是无限制的循环下去的，
     *  使用Timer的cancel()停止操作。当然同一个Timer执行一次cancel()方法后，所有Timer线程都被终止。
     */
    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //获取歌曲时长
                    int duration = mediaPlayer.getDuration();
                    //获取当前播放进度
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    Message message = MainActivity.handler.obtainMessage();
                    //传消息
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    message.setData(bundle);
                    MainActivity.handler.sendMessage(message);
                }
                //开始计时任务  设定时间
            }, 0, 500);
        }
    }

    public void onEvent(MyEvent.PlayMode mode) {
        mPlayMode = mode.getMode();
    }

    /**
     * 带按钮的通知栏
     */
    public void showButtonNotify() {
        mBuilder = new NotificationCompat.Builder(this);
        mRemoteViews = new RemoteViews(getPackageName(), R.layout.notifiton_layout);
        mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.mipmap.musiclogo);
        //API3.0 以上的时候显示按钮，否则消失
        mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, PlayerService.this.getName());
        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, PlayerService.this.getSinger());
        //如果版本号低于（3。0），那么不显示按钮
        if (BaseTools.getSystemVersion() <= 9) {
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);
        } else {
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);
            //
            Log.i("lanou", "---------->>" + prepare);
            if (prepare) {
                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_pause);
            } else {
                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_play);
            }
        }

        //点击的事件处理
        Intent buttonIntent = new Intent(ACTION_BUTTON);
        /* 上一首按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
        //这里加了广播，所及INTENT的必须用getBroadcast方法
        PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1,
                buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);
        /* 播放/暂停  按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2,
                buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
        /* 下一首 按钮  */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
        PendingIntent intent_next = PendingIntent.getBroadcast(this, 3,
                buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);
        /* 清除通知栏 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_EXIT_ID);
        PendingIntent intent_exit = PendingIntent.getBroadcast(this, 4,
                buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_exit, intent_exit);
        /*跳转到Activity*/
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_INTENT_ID);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent intent_intent = PendingIntent.getActivity(this,5,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.intentAci, intent_intent);


        mBuilder.setContent(mRemoteViews)
                .setContentIntent(intent_intent)
                .setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
                .setTicker("正在播放")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.mipmap.musiclogo);
        Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(5, notify);
    }

    /**
     * 带按钮的通知栏点击广播接收
     */
    public void initButtonReceiver() {
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);
    }

    /**
     * 广播监听按钮点击事件
     */
    public class ButtonBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(ACTION_BUTTON)) {
                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
                int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);
                switch (buttonId) {
                    case BUTTON_PREV_ID:
                        Log.d("TAG", "上一首");
                        Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();
                        upSong();
                        break;
                    case BUTTON_PALY_ID:
                        String play_status = "";
                        prepare = !prepare;
                        if (prepare) {
                            play_status = "开始播放";
//                            mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_pause);
//                            Notification notify = mBuilder.build();
//                            notify.flags = Notification.FLAG_ONGOING_EVENT;
//                            mNotificationManager.notify(200, notify);
                            mediaPlayer.start();
                        } else {
                            play_status = "暂停";
                            Log.i("TAG", String.valueOf(mediaPlayer.getDuration()));
//                            mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_play);
//                            Notification notify = mBuilder.build();
//                            notify.flags = Notification.FLAG_ONGOING_EVENT;
//                            mNotificationManager.notify(200, notify);
                            mediaPlayer.pause();
                        }
                        showButtonNotify();
                        Log.d("TAG", play_status);
                        Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();
                        break;
                    case BUTTON_NEXT_ID:
                        Log.d("TAG", "下一首");
                        Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();
                        next();
                        break;
                    case BUTTON_EXIT_ID:
                        Toast.makeText(getApplicationContext(), "清除通知栏", Toast.LENGTH_SHORT).show();
                        clearAllNotify();
                        break;
                    case BUTTON_INTENT_ID:
//                         Intent intent1 = new Intent(context,MainActivity.class);
//                         startActivity(intent1);
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 清除所有通知栏
     */
    public void clearAllNotify() {
        mNotificationManager.cancelAll();// 删除你发的所有通知
    }

    /**
     * @获取默认的pendingIntent,为了防止2.3及以下版本报错
     * @flags属性: 在顶部常驻:Notification.FLAG_ONGOING_EVENT
     * 点击去除： Notification.FLAG_AUTO_CANCEL
//     */
//    public PendingIntent getDefalutIntent(int flags) {
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flags);
//        return pendingIntent;
//    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        unregisterReceiver(bReceiver);
        EventBus.getDefault().unregister(this);//取消订阅
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}

